import requests
import logging
from datetime import datetime
from dateutil.relativedelta import relativedelta

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 微信企业id
WECHAT_CORPID = "wwcxxxxxxxx737d"
# secret
WECHAT_CORPSECRET = "s8kFpC02wB3xxxxxxxxv17lQYFzNCA4"
# 接收者
WECHAT_TOUSER = "User1|User2"
# 应用id
WECHAT_AGENTID = "1000001"
# 彩云天气token
CAIYUN_TOKEN = "qHi1xxxxxxxxWwzPAH"
# 天气城市
CAIYUN_LOCATION = "118.732767,32.168716"
# 黄历key
HUANG_LI_KEY = "929be8axxxxxxxx1ed09c8f8e"

# URL常量
GET_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={}"
SEND_MSG_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}"
CAI_YUN_URL = "https://api.caiyunapp.com/v2.5/{}/{}/daily.json"
YI_YAN_URL = "https://international.v1.hitokoto.cn/?c=h"
HUANG_LI_URL = "http://v.juhe.cn/laohuangli/d?date={}&key={}"
ONE_WORD_URL = "https://api.xygeng.cn/openapi/one"

# 信息常量
TITLE = "亲爱的老婆，早呀🎉"
DESCRIPTION_TEMPLATE = (
    "💖 我们已相爱{loveDays}\n"
    "📅 今天是：{today}\n"
    "📜 农历：{yinLi}\n"
    "🌆 城市：南京\n"
    "🌤️ 天气：{weather}\n"
    "👔 穿衣：{clothingAdvice}\n"
    "🎂 你的生日还有：{birthday} 天\n"
    "🍼 宝宝已经：{babyDays}啦\n"
    "👶 宝宝生日还有：{babyBirthday} 天\n"
    "👰 我们周年还有：{anniversary} 天\n"
    "💬 每日一言：{words}\n"
)
URL = "https://api.03c3.cn/api/zb"
PIC_URL = "https://pic.imgdb.cn/item/6709ed7cd29ded1a8c60b3cd.webp"
BABY_BIRTHDAY = datetime(2024, 1, 10)
BIRTHDAY = datetime(datetime.now().year, 12, 31)
ANNIVERSARY = datetime(datetime.now().year, 12, 31)
LOVEDAY = datetime(2012, 1, 10)

# 获取企微应用发送消息token
def get_access_token():
    url = GET_TOKEN_URL.format(WECHAT_CORPID, WECHAT_CORPSECRET)
    response = requests.get(url)
    data = response.json()

    if data.get("errcode") == 0:
        logger.info("获取 Access Token 成功")
        return data.get("access_token")
    else:
        logger.error("获取 Access Token 失败: %s", data.get("errmsg", "未知错误"))
        return None

# 发送每日问候
def send_daily_greeting():
    access_token = get_access_token()
    if not access_token:
        return

    url = SEND_MSG_URL.format(access_token)

    # 获取天气信息
    weather_response = get_weather()
    daily = weather_response.get("result", {}).get("daily", {})
    temperature = daily.get("temperature", [{}])[0]
    skycon = daily.get("skycon", [{}])[0].get("value", "")

    # 映射天气描述
    weather_desc = map_skycon_to_description(skycon)

    # 获取穿衣建议
    clothing_advice = get_clothing_advice(temperature.get("max", 0))

    # 获取每日一言
    # yiyan_response = get_yiyan()
    # hitokoto = yiyan_response.get("data", {})
    hitokoto = get_yiyan()

    # 获取黄历信息
    huangli_response = get_huangli()
    huangli = huangli_response.get("result", {})

    # 动态生成 description 内容并替换占位符
    description = DESCRIPTION_TEMPLATE.format(
        today=get_today(),
        loveDays=get_love_day(),
        weather=f"{weather_desc} {round(temperature.get('min', 0))} ~ {round(temperature.get('max', 0))} ℃",
        clothingAdvice=clothing_advice,
        yinLi=huangli.get("yinli", ""),
        babyDays=get_baby_age(),
        babyBirthday=get_days_until_baby_birthday(),
        birthday=get_days_until_birthday(),
        anniversary=get_days_until_anniversary(),
        # words=hitokoto.get("content", "")
        words=hitokoto.get("hitokoto", "") + " -- " + hitokoto.get("from", "")
    )

    # 构建消息请求
    request_data = {
        "touser": WECHAT_TOUSER,
        "msgtype": "news",
        "agentid": WECHAT_AGENTID,
        "news": {
            "articles": [
                {
                    "title": TITLE,
                    "description": description,
                    "url": URL,
                    "picurl": PIC_URL
                }
            ]
        }
    }
    logger.info("发送消息信息: %s", description)
    response = requests.post(url, json=request_data)
    if response.status_code == 200:
        logger.info("发送消息成功 返回信息: %s", response.text)
    else:
        logger.error("发送失败")

# 获取彩云天气信息
def get_weather():
    url = CAI_YUN_URL.format(CAIYUN_TOKEN, CAIYUN_LOCATION)
    response = requests.get(url)
    data = response.json()

    if data.get("status") == "ok":
        logger.info("获取彩云天气信息成功")
        return data
    else:
        logger.error("获取彩云天气信息失败")
        raise Exception("获取彩云天气信息失败")

# 映射彩云天气状况描述
def map_skycon_to_description(skycon):
    skycon_map = {
        "CLEAR_DAY": "晴",
        "CLEAR_NIGHT": "晴（夜间）",
        "PARTLY_CLOUDY_DAY": "多云（白天）",
        "PARTLY_CLOUDY_NIGHT": "多云（夜间）",
        "CLOUDY": "阴",
        "LIGHT_HAZE": "轻度雾霾",
        "MODERATE_HAZE": "中度雾霾",
        "HEAVY_HAZE": "重度雾霾",
        "LIGHT_RAIN": "小雨",
        "MODERATE_RAIN": "中雨",
        "HEAVY_RAIN": "大雨",
        "STORM_RAIN": "暴雨",
        "FOG": "雾",
        "LIGHT_SNOW": "小雪",
        "MODERATE_SNOW": "中雪",
        "HEAVY_SNOW": "大雪",
        "STORM_SNOW": "暴雪",
        "DUST": "浮尘",
        "SAND": "沙尘",
        "WIND": "大风"
    }
    return skycon_map.get(skycon, "未知天气")

# 获取每日一言
def get_yiyan():
    response = requests.get(YI_YAN_URL)
    data = response.json()

    if data:
        logger.info("获取每日一言成功")
        return data
    else:
        logger.error("获取每日一言失败")
        raise Exception("获取每日一言失败")

# 获取黄历信息
def get_huangli():
    url = HUANG_LI_URL.format(get_today(), HUANG_LI_KEY)
    response = requests.get(url)
    data = response.json()

    if data:
        logger.info("获取黄历成功")
        return data
    else:
        logger.error("获取黄历失败")
        raise Exception("获取黄历失败")

# 自定义穿衣建议
def get_clothing_advice(max_temp):
    if max_temp <= -10:
        return "长款厚羽绒服、毛衣。"
    elif max_temp < 0:
        return "厚羽绒服、毛衣。"
    elif max_temp < 10:
        return "厚毛衣、风衣或夹克。"
    elif max_temp < 15:
        return "中等厚度毛衣或卫衣、长裤。"
    elif max_temp < 20:
        return "长袖衬衫、薄外套、长裤。"
    elif max_temp < 25:
        return "短袖衬衫T恤、薄长裤。"
    elif max_temp < 30:
        return "短袖衬衫T恤、短裤短裙。"
    else:
        return "短袖T恤、短裤或短裙。"

# 获取今天的日期
def get_today():
    today = datetime.now()
    week_day_map = {
        0: "一",
        1: "二",
        2: "三",
        3: "四",
        4: "五",
        5: "六",
        6: "日"
    }
    week_day = week_day_map[today.weekday()]
    return today.strftime(f"%Y-%m-%d 星期{week_day}")

# 获取宝宝年龄
def get_baby_age():
    today = datetime.now()
    age = relativedelta(today, BABY_BIRTHDAY)
    return f"{age.years}年{age.months}个月{age.days}天"
    
# 获取相爱天数
def get_love_day():
    today = datetime.now()
    age = relativedelta(today, LOVEDAY)
    return f"{age.years}年{age.months}个月{age.days}天"

# 获取距离生日的天数
def get_days_until_birthday():
    if datetime.now() > BIRTHDAY:
        birthday = BIRTHDAY.replace(year=datetime.now().year + 1)
    else:
        birthday = BIRTHDAY
    return (birthday - datetime.now()).days

# 获取距离纪念日的天数
def get_days_until_anniversary():
    if datetime.now() > ANNIVERSARY:
        anniversary = ANNIVERSARY.replace(year=datetime.now().year + 1)
    else:
        anniversary = ANNIVERSARY
    return (anniversary - datetime.now()).days

# 获取距离宝宝生日的天数
def get_days_until_baby_birthday():
    current_year = datetime.now().year
    baby_birthday_this_year = BABY_BIRTHDAY.replace(year=current_year)
    if datetime.now() > baby_birthday_this_year:
        baby_birthday_next_year = BABY_BIRTHDAY.replace(year=current_year + 1)
        return (baby_birthday_next_year - datetime.now()).days
    else:
        return (baby_birthday_this_year - datetime.now()).days

if __name__ == "__main__":
    send_daily_greeting()